<template>
	<div class="container">
		<JxNavbar title="充值" />

		<view class="card">
			<div class="top">
				<text class="tip">金币余额</text>
				<text class="btn" @click="navigateTo('/pages/sub/my/gold/record/index')">金币记录</text>
			</div>
			<text class="price">{{ userInfo['gold'] }}</text>
		</view>

		<view class="price-list">
			<view class="p-item  uv-border" :class="{ active: index === selectIndex }" v-for="(item, index) in quantityList" :key="index"
				@click="checkePrice(index)">
				<text>{{ item }}枚</text>
			</view>
		</view>

		<view class="input-wrap uv-border-bottom">
			<text>其他数量</text>
			<input v-model='quantity' placeholder="请输入其他数量" @input="bindReplaceInput" @focus="focusiInput" :maxlength="10" />
			<text>枚</text>
		</view>

		<div class="pay-type">
			<view class="page-tit">
				<text class="f-b">选择支付方式</text>
			</view>

			<view class="cell uv-border-bottom" @click="payType('money')">
				<image class="icon" :src="$surl('/my/money.png')" mode="heightFix" />
				<div class="main-box">
					<text class="tit">钱包余额</text>
					<text class="tip">({{ userInfo['money'] }}元)</text>
				</div>
				<i class="iconfont" :class="curType === 'money' ? 'icon-chenggong' : 'icon-weixuanzhong'"></i>
			</view>

			<view class="cell uv-border-bottom" @click="payType('wxpay')">
				<image class="icon" :src="$surl('/my/wxpay.png')" mode="heightFix" />
				<div class="main-box">
					<text class="tit">微信支付</text>
				</div>
				<i class="iconfont" :class="curType === 'wxpay' ? 'icon-chenggong' : 'icon-weixuanzhong'"></i>
			</view>
		</div>

		<div class="submit-btn">
			<uv-button shape='circle' :custom-style="{ height: '85rpx' }" type='primary' :text="`确认充值(${money}元)`" @click='onSubmit'></uv-button>
		</div>

		<div class="recharge-tip">
			<div>充值说明：1元可以兑换10枚金币呢。</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed } from 'vue';
import pay from '@/api/pay/index.js';
import tools from '@/utils/tools/index.js';
import orders from '@/api/orders/index.js';
import { useUserStore } from '@/store/user.js';
import JxNavbar from '@/components/navbar/index.vue'

const test = uni.$uv.test;
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo);

const curType = ref('wxpay');
const selectIndex = ref(0);
const quantityList = ref([10, 20, 50, 100, 200, 500, 1000, 1500, 3000, 5000, 10000]);
const quantity = ref(quantityList.value[selectIndex.value]);

const money = computed(() => quantity.value / 10);

const consumeGold = computed(() => generalStore.systemData.gold.publish);

async function onSubmit() {
	let val = money.value;
	if (!test.number(val)) return tools.toast({ title: '请选择或输入充值数量' });

	tools.loading();
	const response = await orders.create({ money: val, type: 'gold' });
	uni.hideLoading();
	if (response['code'] === 200) {
		const order_no = response['data']['order_no'];
		if (curType.value === 'wxpay') {
			toWxPay(order_no);
		} else {
			toWalletBalancePay(order_no);
		}
	}
}

async function toWxPay(order_no) {
	tools.loading();
	const codeResult = await tools.getLoginCode();
	if (codeResult['code'] !== 200) {
		uni.hideLoading();
		return tools.toast({ title: codeResult['err'] });
	}
	const response = await pay.weixin({ order_no, code: codeResult['data'] });
	uni.hideLoading();
	if (response['code'] === 200) {
		const data = response['data']
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: data['timeStamp'],
			nonceStr: data['nonceStr'],
			package: data['package'],
			signType: data['signType'],
			paySign: data['paySign'],
			success: (res) => {
				userStore.init();
				tools.toast({ title: '支付成功', icon: 'success' })
			},
			fail: (err) => {
				tools.toast({ title: '支付失败', icon: 'error' })
			}
		})
	}
}

async function toWalletBalancePay(order_no) {
	tools.loading();
	const response = await pay.walletBalance({ order_no });
	uni.hideLoading();
	if (response['code'] === 200) {
		userStore.init();
		tools.toast({ title: '支付成功', icon: 'success' })
	}
}

function payType(type) {
	if (type === 'money' && userInfo.value.money < money.value) {
		return tools.toast({ title: '钱包余额不足' })
	}
	curType.value = type;
}

function checkePrice(index) {
	selectIndex.value = index;
	quantity.value = quantityList.value[selectIndex.value];
}

// 金额输入框  
function bindReplaceInput(e) {
	const value = e.detail.value;
	const newValue = value.replace(/[^\d]/g, '');
	setTimeout(() => quantity.value = newValue, 10)
}

function focusiInput() {
	selectIndex.value = ''
}

function navigateTo(url) {
	uni.navigateTo({ url })
}
</script>

<style lang="scss" scoped>
.container {
	padding: 0 $side-width;

	.card {
		width: 100%;
		height: 280rpx;
		padding: 40rpx 30rpx;
		background-image: url("https://cdn.jingmingos.com/static/my/wallet.png");
		background-size: 100% 100%;
		color: #fff;
		box-sizing: border-box;
		margin: 20rpx 0 0 0;
		display: flex;
		flex-direction: column;

		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.tip {
				line-height: 40rpx;
				font-size: 36rpx;
			}

			.btn {
				background-color: #e0bb7e;
				padding: 10rpx 40rpx;
				border-radius: 15px;
				font-size: 28rpx;
			}
		}

		.price {
			margin-top: 8rpx;
			font-size: 72rpx;
			line-height: 92rpx;
		}
	}

	.price-list {
		display: flex;
		flex-wrap: wrap;
		padding-top: 40rpx;

		.p-item {
			color: $uv-tips-color;
			width: 23%;
			height: 70rpx;
			border-radius: 3px;
			margin-bottom: 20rpx;
			background-color: $uv-bg-color;
			margin-right: 2.5%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;

			&:nth-child(4n) {
				margin-right: 0;
			}

			&.active {
				color: #fff;
				border-color: $uv-error !important;
				background: linear-gradient(131deg, rgba($uv-error, .6), $uv-error);
			}
		}
	}

	.input-wrap {
		height: 90rpx;
		display: flex;
		align-items: center;

		input {
			flex: 1;
			height: 90rpx;
			font-size: 30rpx;
			padding-left: 30rpx;
			text-align: right;
		}

		text {
			padding: 0 10rpx;

			&:first-child {
				color: $uv-tips-color;
			}
		}
	}

	.pay-type {
		margin-top: 60rpx;

		.page-tit {
			font-weight: 600;
		}

		.cell {
			display: flex;
			align-items: center;
			height: 124rpx;
			padding-right: 6rpx;

			.icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 16rpx;
			}

			.main-box {
				flex: 1;
				display: flex;
				align-items: center;

				.tit {
					font-size: 30rpx;
					font-weight: 600;
				}

				.tip {
					font-size: 28rpx;
					color: $uv-tips-color;
					margin-left: 10rpx;
				}
			}

			.iconfont {
				color: $uv-tips-color;
				font-size: 40rpx;
			}

			.icon-chenggong {
				color: $uv-primary;
			}
		}
	}

	.submit-btn {
		padding-top: 6vh;
	}

	.recharge-tip {
		font-size: 28rpx;
		color: $uv-tips-color;
		margin-top: $side-width;
		text-align: center;
	}
}
</style>